package cn.tedu.shoppingmall.filter;

import cn.tedu.shoppingmall.vo.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "UserFilter",urlPatterns = {"/adminindex.html","/addCommodity.html","/updateCommodity.html"})//"/admin/*","/adminindex.html","/addCommodity.html","/updateCommodity.html"
public class UserFilter implements Filter {
    //过滤器初始化时执行的方法
    public void init(FilterConfig config) throws ServletException {

    }
    //过滤器销毁时执行的方法
    public void destroy() {

    }

    @Override//执行Controller方法之前和之后执行的方法
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        chain.doFilter(request, response);
        System.out.println("------------------------------------------>>>>filter");
        //开始是object型的,需要转换
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        //得到Session会话对象
        HttpSession session = request1.getSession();
        //得到登录的用户对象
        User u = (User) session.getAttribute("u");
        if (u!=null){//登录了
            chain.doFilter(request,response);
        }else{ //让客户端跳转到登录页面
            response1.sendRedirect("/admin/adminLogin.html");
        }
    }
}
